package spring.interceptor;


import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import spring.interceptor.annotations.LoginToken;
import spring.interceptor.annotations.PassToken;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 返回json的Api接口拦截器
 * @author huangqiankun
 * @date 2020年5月7日上午11:09:10
 */
public class ApiInterceptor implements HandlerInterceptor {
	
	/**
	 * 执行控制器之后且在完成渲染视图后调用此方法
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 执行控制器之后且在渲染视图前调用此方法
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//移除虚假的管理员用户
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * 执行控制器之前调用此方法
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 如果不是映射到方法直接通过
        if(handler instanceof HandlerMethod){
        	HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //检查是否有passtoken注释，有则跳过认证
            if (method.isAnnotationPresent(PassToken.class)) {
            	
            }else {
            	//检查有没有需要用户权限的注解
                LoginToken loginToken = null;
                if (method.isAnnotationPresent(LoginToken.class)) {
                	loginToken = method.getAnnotation(LoginToken.class);
                }else if (method.getDeclaringClass().isAnnotationPresent(LoginToken.class)){
                	loginToken = method.getDeclaringClass().getAnnotation(LoginToken.class);
                }
                if (loginToken != null) {
                	String token = request.getHeader("token");// 从 http 请求头中取出 token
                	// 执行认证
                    if (token == null) {
                    	throw new IllegalArgumentException("无token，请登录！");
                    }

					/**
					 * 具体验证 token 是否有效(合法)
					 */


				}
			}
		}

		return HandlerInterceptor.super.preHandle(request, response, handler);
	}
	
}
